<?php
namespace control;
/*
*委外加工费类
*/

class outsourceFeeClass extends adIndexClass
{
    private const page = 'outsourceFee';
    private const title = '委外加工费';
    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            text(array("name" => "orderNo",  "title" => "报工单号")).
            selectMultiple(["name" => "supplierId", 'where' => "coid = '" . self::$coid . "' and outsource= '是' and state = '启用'", 'table' => "supplier", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '委外单位']).
            select(array('name'=>'payState','title'=>'拨付状态','option'=>['未拨付','已拨付'])).
            text(array("name" => "createTime", 'class'=>'width200','laydate' => ['type' => 'date', 'range' => '~'], "title" => "日期-日期"));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.orderNo"=>$this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "b.classify"=>'委外报工',
            "b.coid"=>self::$coid,
            "b.state"=>'已确认',
            "b.companyId"=>$this->post('supplierId')
        );
        $and ="";
        if ($this->post('createTime')) {
            $and.=self::timeComparison($this->post('createTime'),field: 'teamNo');
        }
        if ($this->post('payState') =='未拨付'){
            $and .=" and b.id not in (select targetId from outsource_fee where coid = '".self::$coid."')";
        }elseif($this->post('payState') =='已拨付'){
            $and .=" and b.id in (select targetId from outsource_fee where coid = '".self::$coid."')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => "process_report as b join machining_send_order as ma on ma.id = b.sendId",
            'field'=>"b.*,ma.unit as fromUnit,ma.machiningOrderMxId,ma.orderNo as sendNo","where" => $where, "order" => "b.orderNo desc"));
        static::rSet(self::$stid.self::page.'Sql', $page['fullSql']);
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll,"日期",'报工单号','委外单位', '派工单号', '生产计划单号','工序',  '产品编码', '产品名称', '规格型号', '计件单位', '产量', '加工费','拨付状态');
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $material = query('material',"id = '$array[materialId]'");
            $machiningOrderMx = query('machining_order_mx',"id = '$array[machiningOrderMxId]'");
            $machiningOrder = query('machining_order',"id = '$machiningOrderMx[orderId]'");
            $process = query('process',"id = '$array[processId]'");
            $array['yield'] = machiningOrderClass::material_num_change($array['materialId'],$array['fromUnit'],$material['unit'],$array['yield']);
            $supplier = query('supplier',"id = '$array[companyId]'");
            if (static::total(array('table'=>'outsource_fee','where'=>"targetId = '$array[id]'")) >0){
                $payState = '已拨付';
            }else{
                $payState = '未拨付';
            }

            $tr[] = array($this->dominate($dominate),
                date('Y-m-d',strtotime($array['time'])),
                $array['orderNo'],
                $supplier['name'],
                $array['sendNo'],
                $machiningOrder['orderNo'],
                $process['name'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                self::lostZero($array['yield'],'numPrecision'),
                self::lostZero($array['fee']),
                $payState
            );
        }
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        if ($this->power(self::page, "pay")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'pay', {})\">批量拨付</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 其实目前可以更改，只需删除对应记录即可，给个提示吓唬吓唬
     * 拨付
     * @return bool|string
     */
    public function pay()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                '提示' => " 是否确定已付款所选的加工费，一旦拨付成功，将不可更改？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "拨付", "height" => 160, "width" => 600, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 拨付编辑
     * @return bool|string
     */
    public function payEdit()
    {
        $listId = $this->post('listId');
        if (!$this->power(self::page, "pay")) {
            $json['warn'] = "你没有" . self::title . "的拨付权限";
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = "请选择数据";
        }else {
            $x = 0;
            foreach ($listId as $id) {
                $info = query('process_report', " id = '$id'");
                if ($info['id'] && static::total(array('table'=>'outsource_fee','where'=>"targetId = '$info[id]'")) ==0){
                    $warn = insert(array(
                        "table" => 'outsource_fee',
                        "field" => [
                            'id'=>suiji(),
                            'coid'=>self::$coid,
                            'targetId'=>$info['id'],
                            'supplierId'=>$info['companyId'],
                            'materialId'=>$info['materialId'],
                            'processId' => $info['processId'],
                            'unit' => $info['unit'],
                            'num' => $info['yield'],
                            'money' => $info['fee'],
                            'stid'=>self::$stid,
                        ],
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        //添加日志
                        $text = $this->control['name'] . "生成了委外加工单【{$info['orderNo']}】的加工费记录，id：【" . $id . '】';
                        $this->logText(["type" => self::page, "text" => $text]);
                    }
                }
            }
            //返回
            $_SESSION['warn'] = "成功拨付了{$x}条数据";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }
    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $sql = static::rGet(self::$stid.self::page.'Sql');
            $title =array("日期",'报工单号','委外单位',  '派工单号', '生产计划单号','工序',  '产品编码', '产品名称', '规格型号', '计件单位', '产量', '加工费','拨付状态');
            $result = sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $material = query('material',"id = '$array[materialId]'");
                    $machiningOrderMx = query('machining_order_mx',"id = '$array[machiningOrderMxId]'");
                    $machiningOrder = query('machining_order',"id = '$machiningOrderMx[orderId]'");
                    $process = query('process',"id = '$array[processId]'");
                    $array['yield'] = machiningOrderClass::material_num_change($array['materialId'],$array['fromUnit'],$material['unit'],$array['yield']);
                    $supplier = query('supplier',"id = '$array[companyId]'");
                    if (static::total(array('table'=>'outsource_fee','where'=>"targetId = '$array[id]'")) >0){
                        $payState = '已拨付';
                    }else{
                        $payState = '未拨付';
                    }

                    $tr[] = array(
                        date('Y-m-d',strtotime($array['time'])),
                        $array['orderNo'],
                        $supplier['name'],
                        $array['sendNo'],
                        $machiningOrder['orderNo'],
                        $process['name'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        self::lostZero($array['yield'],'numPrecision'),
                        self::lostZero($array['fee']),
                        $payState
                    );
                }
            }
            $text = $this->control['name'] . "导出了委外加工费表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "委外加工费表.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}

